package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.pojo.Item;
import com.hmall.search.constant.MqConstants;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MqListener {
    @Autowired
    private SearchService searchService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ItemClient itemClient;

    /**
     * 监听新增和修改队列
     *
     * @param itemId
     */
    @RabbitListener(queues = MqConstants.HMALL_INSERT_QUEUE)
    public void hmallInsertAndUpdateQueueListener(Long itemId){
        try {
            Item item = itemClient.selectItem(itemId);
            ItemDoc itemDoc = new ItemDoc(item);
            //索引库名
            IndexRequest indexRequest = new IndexRequest("hmall").id(item.getId().toString());
            indexRequest.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 监听删除队列
     *
     * @param itemId
     */
    @RabbitListener(queues = MqConstants.HMALL_DELETE_QUEUE)
    public void hmallDeleteQueueListener(Long itemId){
        try {
            DeleteRequest deleteIndexRequest = new DeleteRequest("hmall",String.valueOf(itemId));
            restHighLevelClient.delete(deleteIndexRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
